<?php
class EmployeeController extends AppController {
    public $helpers = array('Html', 'Form', 'Navigation');
    public $name = 'Employee';
    var $components = array('CAS_Auth','Session', 'Navigation');
    //models used by this controller
    var $uses = array('Manager','Employee','Hour');
    public function beforeFilter(){
		$this->CAS_Auth->checkAuthentication();
		$this->account = $this->CAS_Auth->getGTAccount();
		$this->set('gtAccount', $this->account);

		//use authentication to display appropriate menu
		$this->permissions = array();
		if($this->Manager->find('count', array('conditions'=> array('Manager.name' => $this->account))) > 0)
			$this->permissions[] = 'manager';
		$this->emp = $this->Employee->find('first', array(
					'conditions'=> array('Employee.name' => $this->account),
					'recursive'=> -1,
		));
		if($this->emp)
			$this->permissions[] = 'employee';
		else
			$this->redirect('/');

		$this->set('navMenu', $this->Navigation->getTree($this->permissions));
    }
    
    /**
    * Sets up information for the view.  Makes employee, hour
    * and project variables
    **/
    function setUpEmployee()
    {
    	$this->set('employee', $this->emp);
	$this->id = $this->emp['Employee']['employee_id'];
	$this->set('empId', $this->id);
	$projects = $this->Employee->Projects->find('all', array(
				'contain' => 'Employees.employee_id = '.$this->id
				)
			);
	//filter out projects without membership, unwrap data
	foreach($projects as $index=>&$project){
		if(!count($project['Employees']))
			unset($projects[$index]);
		else
			$project = $project['Projects'];
	}
        $this->set('projects', $projects);
    }

    function index()
    {
        $this->setUpEmployee();
    }

    function currentlyworking(){
	$this->setUpEmployee();
	$working = array();
	$emps = $this->Employee->find('all');
	foreach($emps as $emp){
		if($this->Employee->currentlyIn($emp['Employee']['employee_id'])){
			$working[] = $emp;
		}
	}
	$this->set('emps',$working);
    }

    //saves a new hour entry using data received from the view
    function clock()
    {
        $this->setUpEmployee();

        if ($this->request->is('post'))
        {
            $clockIn = $this->request->data['employee']['clock_in'];
            $empID= $this->request->data['employee']['employee_id'];
            $projID= $this->request->data['employee']['proj_id'];
            if ($this->Employee->clock($clockIn,$empID,$projID)){
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                echo "<script language>alert('Clock In or Clock out was unsuccessful, ensure a project was selected')</script>";
            }
        } 
    }


    //gets previously made requests for an employee
    function requests()
    {
        $this->setUpEmployee();
        
	    $employee=$this->Employee->find('first', array('conditions'=> array('Employee.name' => $this->account)));
        $emp_id = $employee['Employee']['employee_id']; 
        $requests = array();
        foreach($this->Employee->Request->find('all', array('conditions'=>
                array('Request.employee_id' => $emp_id))) as $request):
	  //get name of manager rather than ID
          if($request['Request']['resolved_by']!='')
          {
                $request['Request']['resolved_by'] = $this->getName($request['Request']['resolved_by']);
          }
		//get project name rather than ID
                $request['Request']['proj_id'] = $this->getProjectName($request['Request']['proj_id']);
		//display IN or OUT rather than 1 or 0 for clock in/out
                $request['Request']['clock_in'] = $request['Request']['clock_in'] == 1 ? 'IN' : 'OUT';
            $requests[] = $request;
        endforeach;
        $this->set('requests',$requests);
    }


    //get all hour entries for an employee for a particular week, and calculate logged time for that week
    function hours($weekId = 0){
	    $this->setUpEmployee();
	    //start of week
	    $currentWeekStart = date('Y-m-d', strtotime('Monday this week'));
	    //start of target week
	    $lowerTimeBound = date('Y-m-d', (strtotime($currentWeekStart) - $weekId*(7 * 24 * 60 * 60)));
	    //end of target week
	    $upperTimeBound = date('Y-m-d', (strtotime($lowerTimeBound)+(7*24*60*60)));
	    $conditions =  array(
			    "Hour.date >=" => $lowerTimeBound,
			    "Hour.date <" => $upperTimeBound,
			    "Hour.employee_id " => $this->id,
			    "Hour.replaced_by"=>null
			    );
	    //total the hours worked during the target week
	    $hours = $this->Hour->find('all',array('conditions'=>$conditions,'order'=>array('Hour.date ASC'))); 
	    $total = 0;
	    $in;
	    $out;
	    $state = 0;
	    //Filter array, clean times & add properties to each hour
	    foreach($hours as &$hour){
		    if($state==0){
			    if(!empty($hour['Hour']['clock_in'])){
				    $state=1;
				    $in = $this->Hour->ClosestQuarter($hour['Hour']['date']);
			    }
		    }
		    else if(!empty($hour['Hour']['clock_in'])){
			    $in = $this->Hour->ClosestQuarter($hour['Hour']['date']);
		    } else{
			    $out = $this->Hour->ClosestQuarter($hour['Hour']['date']);
			    $total+= (($out-$in)/3600);
			    $state=0;
		    }
		    $hour['Hour']['created_by'] = $this->getName($hour['Hour']['created_by']);
		    $hour['Hour']['proj_name'] = $this->getProjectName($hour['Hour']['proj_id']);
		    //$hour['Hour']['date'] = date('Y-m-d H:i:s',($this->Hour->ClosestQuarter($hour['Hour']['date'])));
		    $hour['Hour']['date'] = date('r',($this->Hour->ClosestQuarter($hour['Hour']['date'])));
	    }

	    //send data to view
	    $this->set('upper',date('m-d-Y',strtotime($upperTimeBound)));
	    $this->set('lower',date('m-d-Y',strtotime($lowerTimeBound)));
	    $this->set('total',$total);
	    $this->set('hours',$hours);
	    $this->set('weekId',$weekId);
    }

    //creates a new request for an hour edit
    function makerequest($replaces = null)
    {
        $this->setUpEmployee();
	//modify existing Hours entry
        if ($replaces != null)
        {
           $replaceHour= $this->Employee->Hour->find('first', array(
            'conditions' =>array(
                'Hour.trans_id' => $replaces
            )));
        }
	//request new Hours entry
        else{
                 $this->redirect(array('action' => 'newhourrequest'));
        }
        $this->set('replaces',$replaces); 
        $this->set('replaceHour',$replaceHour['Hour']);
        if ($this->request->is('post'))
        {
	    //add entry to requests table using data received from view
            if($this->Employee->Request->Save(array(
                'clock_in' => $this->request->data['Request']['clock_in'], 
                'employee_id' => $this->request->data['Request']['employee_id'], 
                'replaces' => $this->request->data['Request']['replaces'], 
                'proj_id' => $this->request->data['Request']['proj_id'], 
                'comment' => $this->request->data['Request']['comment'], 
                'approved' => false,
                'date' => $this->request->data['Request']['datetime']
                )
            )){
                 $this->redirect(array('action' => 'requests'));
            }
            else
            {
                echo "<script language>alert('There was an ambiguous problem')</script>";
            }
        }

    }

    //requests a new hour entry for the employee
    function newHourRequest()
    {
        $this->setUpEmployee();
        if ($this->request->is('post'))
        {
	    //creates new request entry using data received from view
            if($this->Employee->Request->Save(array(
                'clock_in' => $this->request->data['Request']['clock_in'], 
                'employee_id' => $this->request->data['Request']['employee_id'], 
                'proj_id' => $this->request->data['Request']['proj_id'], 
                'comment' => $this->request->data['Request']['comment'], 
                'approved' => false,
                'date' => $this->request->data['Request']['datetime']
                )
            )){
                 $this->redirect(array('action' => 'requests'));
            }
            else
            {
                echo "<script language>alert('There was a problem')</script>";
            }
        }


    }

    //return name of manager, employee, or admin
    private function getName($ID){
        $countEmployee= $this->Employee->find('first',array('conditions'=>
            array('Employee.employee_id' => $ID)
        ));
        $name = '';
        if( $countEmployee > 0){
            $employee = $this->Employee->find('first',array('conditions'=>
                array('Employee.employee_id' => $ID)
            ));
            $name = $employee['Employee']['name'];
        }
        else{
             $manager= $this->Manager->find('first',array('conditions'=>
                array('Manager.manager_id' => $ID)
            ));
            $name = $manager['Manager']['name'];

        }
        return $name;
    }
    //return description of a project
    public function getProjectName($projID){
	    $project = $this->Employee->Projects->find('first',array(
				    'conditions'=> array('Projects.project_id' => $projID),
				    'recursive' => -1,
				    ));
	    $name = $projID; //default response
	    if (isset($project['Projects']['description'])){
		    $name = $project['Projects']['description'];
	    }
	    return $name;
    }

}
